package cc.wfu.domain.order.service.rule.chain;

import cc.common.types.entity.ProductActivityEntity;
import cc.wfu.domain.order.model.entity.ProductActivitySkuEntity;
import cc.wfu.domain.order.model.valobj.ActivitySkuStockKeyVO;
import cc.wfu.domain.order.repository.IProductActivityRepository;
import cc.wfu.domain.order.service.rule.AbstractActionChain;
import cc.wfu.domain.order.service.rule.armory.IProductActivityDispatch;
import cc.wfu.types.common.Constants;
import cc.wfu.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc:
 * @Date: 2024-04-23-15:14
 */
@Slf4j
@Component(value = "activity_sku_stock_action")
public class ActivitySkuStockActionChain extends AbstractActionChain {

    @Resource
    private IProductActivityDispatch activityDispatch;
    @Resource
    private IProductActivityRepository repository;

    /**
     * 下单库存过滤
     * @param activitySkuEntity sku订单实体
     * @param activityEntity 活动实体
     * @return 过滤结果
     */
    @Override
    public boolean action(ProductActivitySkuEntity activitySkuEntity, ProductActivityEntity activityEntity) {
        log.info("活动责任链-商品库存处理【校验&扣减】开始。");
        // 扣减库存
        ActivitySkuStockKeyVO activitySkuStockKeyVO = ActivitySkuStockKeyVO.builder()
                .sku(activitySkuEntity.getSku())
                .productId(activityEntity.getProductId())
                .build();
        boolean status = activityDispatch.subtractionActivitySkuStock(activitySkuStockKeyVO, activityEntity.getEndDateTime());
        if (status) {
            // 库存扣减成功
            log.info("活动责任链-商品库存处理【有效期、状态、库存(sku)】成功。sku:{} productId:{}", activitySkuEntity.getSku(), activityEntity.getProductId());
            // 写入延迟队列，延迟消费更新库存记录
            repository.activitySkuStockConsumeSendQueue(activitySkuStockKeyVO);
            return true;
        }

        throw new AppException(Constants.ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getCode(),Constants.ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getInfo());
    }
}
